<template>
  <div class="task">
    <c-section title="门店建设基本信息">
      <template v-slot:right>
        <c-abnormal-preview path="/storeConstruction/exceptionManage" :query="{ constCode: detail.constCode, functionModel: 'SHOP_DECORATION' }" />
      </template>
      <c-list :column="3">
        <c-list-item label="门店建设项目号" :value="detail.constCode" />
        <c-list-item label="门店编码" :value="detail.shopCode" />
        <c-list-item label="门店" :value="detail.shopName" />
        <c-list-item label="所属客户编码" :value="detail.clientCode" />
        <c-list-item label="所属客户" :value="detail.clientName" />
        <c-list-item label="所属办事处" :value="detail.officeName" />
        <c-list-item label="门店类型" dict-type-code="SHOP_TYPE" :value="detail.shopType" />
        <c-list-item label="门店业务类型" dict-type-code="BIZ_TYPE" :value="detail.shopBizType" />
        <c-list-item label="门店城市级别" dict-type-code="CITY_LEVEL" :value="detail.shopCityLevel" />
        <c-list-item label="门店详细地址" :value="detail.shopAddress" :span="3" />
        <c-list-item label="报图类型" dict-type-code="MARKET_TYPE" :value="detail.marketType" />
        <c-list-item label="门店建设类型" dict-type-code="CONST_TYPE" :value="detail.constType" />
        <c-list-item label="商家类别" dict-type-code="BIZMAN_TYPE" :value="detail.bizmanType" />
        <c-list-item label="装修形式" dict-type-code="DECORATION_FORM" :value="detail.decorationForm" />
        <c-list-item label="门店建设范围" dict-type-code="DECORATION_RANGE" :value="detail.decorationRange" />
      </c-list>
    </c-section>
    <c-section title="装修申请信息">
      <c-list ref="info" :column="3" :model="detail" :rules="formRules" label-width="100px">
        <c-list-item label="本次装修范围" prop="range">
          <c-dict-checkbox-select v-model="detail.range" :includes="range" dict-type-code="DECORATION_RANGE" />
        </c-list-item>
        <c-list-item label="装修形式" dict-type-code="DECORATION_FORM" :value="detail.decorationFormCal" />
        <c-list-item label="装修性质" prop="nature">
          <c-dict-select v-model="detail.nature" dict-type-code="DECORATION_NATURE" />
        </c-list-item>
      </c-list>
    </c-section>
    <c-section title="现场开工条件判断">
      <c-list ref="startCondition" :column="1" :model="detail" :rules="formRules" label-width="135px">
        <template v-if="detail.range.includes('STORES')">
          <!-- <c-list-item class="err-offset" prop="constPicRemark">
            <c-checkbox-remark v-model="detail.startCondition.constPicRemark" :remark.sync="detail.constPicRemark" label="施工图纸确定" remark-label="施工图纸备注" label-width="200px" remark-label-width="100px" />
          </c-list-item> -->
          <c-list-item class="err-offset" prop="acRemark">
            <c-checkbox-remark v-model="detail.startCondition.acRemark" :remark.sync="detail.acRemark" label="空调符合装修标准" remark-label="空调备注" label-width="200px" remark-label-width="100px" />
          </c-list-item>
          <c-list-item class="err-offset" prop="wpRemark">
            <c-checkbox-remark v-model="detail.startCondition.wpRemark" :remark.sync="detail.wpRemark" label="防水符合装修标准" remark-label="防水备注" label-width="200px" remark-label-width="100px" />
          </c-list-item>
          <c-list-item class="err-offset" prop="fcRemark">
            <c-checkbox-remark v-model="detail.startCondition.fcRemark" :remark.sync="detail.fcRemark" label="消防符合装修标准" remark-label="消防备注" label-width="200px" remark-label-width="100px" />
          </c-list-item>
          <c-list-item class="err-offset" prop="horizonRemark">
            <c-checkbox-remark v-model="detail.startCondition.horizonRemark" :remark.sync="detail.horizonRemark" label="地平已找平" remark-label="地平备注" label-width="200px" remark-label-width="100px" />
          </c-list-item>
        </template>
        <c-list-item label="预计进场装修时间" prop="expectDecorationTime" :span="1/3">
          <el-date-picker
            v-model="detail.expectDecorationTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item label="预计开业时间" prop="expectOpenTime" :span="1/3">
          <el-date-picker
            v-model="detail.expectOpenTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item label="装修申请审核通过时间" prop="decorationApplyPassTime" :span="1/3">
          <el-date-picker
            v-model="detail.decorationApplyPassTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item label="申请说明" prop="expectDesc">
          <el-input v-model="detail.expectDesc" type="textarea" :autosize="{minRows: 3}" maxlength="1024" show-word-limit placeholder="申请说明" clearable />
        </c-list-item>
      </c-list>
    </c-section>
    <c-section title="装修跟进信息">
      <c-list ref="followUp" :column="3" :model="detail" :rules="formRules" label-width="140px">
        <!-- // 1.装修进度默认不可选择，提交时根据装修步骤自动填充； -->
        <c-list-item prop="schedule" label="装修进度">
          <c-dict-select v-model="detail.schedule" disabled dict-type-code="DECORATION_SCHEDULE" placeholder="请选择" />
        </c-list-item>
        <c-list-item prop="steps" label="装修步骤">
          <c-dict-select v-model="detail.steps" exclude="M1" dict-type-code="SHOP_DECORATION_STEPS" placeholder="请选择" @change="stepsChangeHandle" />
        </c-list-item>
        <c-list-item prop="state" label="装修状态">
          <c-dict-select v-model="detail.state" dict-type-code="SHOP_DECORATION_STATE" placeholder="请选择" />
        </c-list-item>
        <c-list-item prop="constUnitCode" label="施工单位">
          <c-single-dialog
            ref="constUnitCode"
            v-model="detail.constUnitCode"
            :label.sync="detail.constUnitName"
            :props="{label:'unitName',value:'unitCode'}"
            :focus-query="true"
            :multiple="false"
            :config="{
              title:'施工单位',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/shopDecoration/pageUnitPupSelect',
              method:'post',
              filtersRaw:[],
              paramsRaw:{schedule: 'L'},
              setting:[
                {prop:'unitCode',title:'编码',width:80},
                {prop:'unitName',title:'名称',width:200}
              ]
            }"
          />
        </c-list-item>
        <c-list-item prop="proSupervisorCode" label="工程监理">
          <c-single-dialog
            ref="proSupervisorCode"
            v-model="detail.proSupervisorCode"
            :label.sync="detail.proSupervisorName"
            :props="{label:'userName',value:'account'}"
            :focus-query="true"
            :multiple="false"
            :config="{
              title:'工程监理',
              width:'600px',
              interfacePath:`/slm-admin/api/v1/user/listUsers`,
              method:'post',
              filtersRaw:[],
              paramsRaw:{},
              setting:[
                {prop:'account',title:'编码',width:80},
                {prop:'userName',title:'名称',width:200}
              ]
            }"
            @change="changeData1"
          />
          <c-list-item label="工程监理部门">
            {{ orgInfo1 }}
          </c-list-item>
        </c-list-item>
        <c-list-item prop="formSupervisorCode" label="形象督导">
          <c-single-dialog
            ref="formSupervisorCode"
            v-model="detail.formSupervisorCode"
            :label.sync="detail.formSupervisorName"
            :props="{label:'userName',value:'account'}"
            :focus-query="true"
            :multiple="false"
            :config="{
              title:'形象督导',
              width:'600px',
              interfacePath:`/slm-admin/api/v1/user/domainUser/page`,
              method:'post',
              filtersRaw:[],
              paramsRaw:{},
              setting:[
                {prop:'account',title:'编码',width:80},
                {prop:'userName',title:'名字',width:150},
                {prop: 'phone', title: '电话', width: 150}
              ]
            }"
            @change="changeData2"
          />
        </c-list-item>
        <c-list-item label="形象督导部门">
          {{ orgInfo2 }}
        </c-list-item>
        <c-list-item prop="actualApproachTime" label="实际进场时间">
          <el-date-picker
            v-model="detail.actualApproachTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="startMeetingHoldTime" label="开工启动会议召开时间">
          <el-date-picker
            v-model="detail.startMeetingHoldTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="expectEndTime" label="预计完工时间">
          <el-date-picker
            v-model="detail.expectEndTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="hiddenProAcceptTime" label="隐蔽工程验收时间">
          <el-date-picker
            v-model="detail.hiddenProAcceptTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="proRerulerTime" label="产品复尺时间">
          <el-date-picker
            v-model="detail.proRerulerTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="initInspectionTime" label="初检时间">
          <el-date-picker
            v-model="detail.initInspectionTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="actualEndTime" label="实际装修完工时间">
          <el-date-picker
            v-model="detail.actualEndTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="stopTime" label="暂停时间">
          <el-date-picker
            v-model="detail.stopTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="expectRestoreTime" label="预计恢复时间">
          <el-date-picker
            v-model="detail.expectRestoreTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="acceptTaskCode" label="验收任务号">
          <el-input v-model="detail.acceptTaskCode" placeholder="请输入" clearable />
        </c-list-item>
        <c-list-item prop="actualInspectionTime" label="实际报验时间">
          <el-date-picker
            v-model="detail.actualInspectionTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="decorationClosedType" label="结案类型">
          <c-dict-select v-model="detail.decorationClosedType" dict-type-code="DECORATION_CLOSED_TYPE" placeholder="请选择" />
        </c-list-item>
        <c-list-item prop="mustRectifyEndTime" label="应整改完成时间">
          <el-date-picker
            v-model="detail.mustRectifyEndTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="acceptEndTime" label="验收结案时间">
          <el-date-picker
            v-model="detail.acceptEndTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item prop="shopDecorationArea" label="卖场装修区域">
          <c-remote-select v-model="detail.shopDecorationArea" url="/api/v1/configArea/page" label-name="areaName" value-name="areaCode" multiple />
        </c-list-item>
        <c-list-item prop="shopDecorationTotalArea" label="卖场装修总面积">
          <c-input-number v-model="detail.shopDecorationTotalArea" placeholder="请输入" clearable />
        </c-list-item>
        <c-list-item prop="dheadDecorationTotalArea" label="门头装修总面积">
          <c-input-number v-model="detail.dheadDecorationTotalArea" placeholder="请输入" clearable />
        </c-list-item>
      </c-list>
    </c-section>
    <RD title="关联图纸" interface-path="/slm-admin/api/v1/shopDesignPicture/getUnConnectPic" :other-filters="otherFilters" :data="drawData" @change="changeDrawingHandle" />
    <c-section style="padding-bottom:50px" title="上传附件">
      <c-file-table-box v-model="files" belong-model="SHOP_DECORATION" :model-id="$route.query.id" />
    </c-section>
    <div class="footer-btn">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">确定</c-button>
    </div>
  </div>
</template>
<script>
import { getOrgByAccount } from '@/api/common'
import RD from './addEdit/components/rd'
import { postAddTask, getGetOneByid, postSelectByModelId, postConfigAttachmentTemplate } from '@/api/decorate'
import { otherFiltersItem, deepClone } from '@/utils'
export default {
  name: 'DecorateTaskAdd',
  components: {
    RD
  },
  data() {
    // 验证预计装修进场时间
    const validatorEDT = (r, v, c) => {
      const { expectDecorationTime, expectOpenTime } = this.detail
      if (expectDecorationTime && expectOpenTime) {
        const edt = new Date(expectDecorationTime).getTime()
        const eot = new Date(expectOpenTime).getTime()
        if (edt > eot) {
          c(new Error('预计进场装修时间不能大于预计开业时间'))
        } else {
          c()
        }
        return
      }
      c()
    }
    const validatorConst = key => {
      return (r, v, c) => {
        if (!this.detail.startCondition[key] && (v === '' || v === undefined)) {
          c(new Error('请输入备注'))
        } else {
          c()
        }
      }
    }
    return {
      orgInfo1: '',
      orgInfo2: '',
      files: [],
      drawData: [],
      range: [],
      detail: {
        formSupervisorCode: '',
        formSupervisorName: '',
        range: [],
        nature: '',
        // 现场开工条件判断
        startCondition: {
          constPicRemark: false,
          acRemark: false,
          wpRemark: false,
          fcRemark: false,
          horizonRemark: false
        },
        constPicRemark: '',
        acRemark: '',
        wpRemark: '',
        fcRemark: '',
        horizonRemark: '',
        expectOpenTime: '',
        expectDecorationTime: '',
        decorationApplyPassTime: '',
        expectDesc: '',
        // 关联图纸
        designPictureDTOS: [],
        shopDecorationArea: []
      },
      formRules: {
        range: [{ required: true, message: '请优先选择门店建设项目号', trigger: 'change' }],
        expectDesc: [{ required: true, message: '请填写申请说明', trigger: 'change' }],
        nature: [{ required: true, message: '请选择装修性质', trigger: 'change' }],
        expectDecorationTime: [
          { required: true, message: '请预计进场装修时间', trigger: 'change' },
          { required: true, validator: validatorEDT, trigger: 'change' }
        ],
        expectOpenTime: [
          { required: true, message: '请选择预计开业时间', trigger: 'change' },
          { required: true, validator: validatorEDT, trigger: 'change' }
        ],
        // 条件
        constPicRemark: [{ required: false, validator: validatorConst('constPicRemark'), trigger: 'blur' }],
        acRemark: [{ required: true, validator: validatorConst('acRemark'), trigger: 'blur' }],
        wpRemark: [{ required: true, validator: validatorConst('wpRemark'), trigger: 'blur' }],
        fcRemark: [{ required: true, validator: validatorConst('fcRemark'), trigger: 'blur' }],
        horizonRemark: [{ required: true, validator: validatorConst('horizonRemark'), trigger: 'blur' }]
      },
      aTList: []
    }
  },
  computed: {
    //  1.图纸数据展示范围：所有图纸类型为”施工图“，且图纸进度值为”已完成“的图纸；
    otherFilters() {
      return [
        otherFiltersItem('picType', 'SG', '='),
        otherFiltersItem('schedule', 'F', '='),
        otherFiltersItem('isOutpicUndecoration', '0', '='),
        otherFiltersItem('constCode', this.detail.constCode, '=')
      ]
    }
  },
  created() {
    this.getDetail().then(() => {
      // detail.startCondition
      for (const k of Object.keys(this.detail.startCondition || {})) {
        this.$watch(`detail.startCondition.${k}`, (n, o) => {
          this.$nextTick(() => {
            this.$refs.startCondition.validateField([k])
          })
        })
      }
    })
    this.getTemplate()
  },
  methods: {
    changeData1(data) {
      getOrgByAccount(data.account).then(res => {
        if (res.success === 1) {
          if (res.data.length !== 0) {
            const list = res.data.map(el => el.orgName)
            this.orgInfo1 = list.join(',')
          } else {
            this.orgInfo1 = ''
          }
        }
      })
    },
    changeData2(data) {
      getOrgByAccount(data.account).then(res => {
        if (res.success === 1) {
          if (res.data.length !== 0) {
            const list = res.data.map(el => el.orgName)
            this.orgInfo2 = list.join(',')
          } else {
            this.orgInfo2 = ''
          }
        }
      })
    },
    // 设置类型数据
    constCodeChangeHandle(data) {
      const keys = this.$split('bizmanType clientCode clientName constCode constType decorationForm decorationRange marketType officeCode officeName shopAddress shopBizType shopCityLevel shopCode shopName shopType', ' ')
      for (const key of keys) {
        let v = data[key]
        if (key === 'decorationRange') {
          v = this.$split(v)
          this.range = deepClone(v)
          this.$set(this.detail, 'range', deepClone(v))
        }
        this.$set(this.detail, key, v || '')
      }
    },
    detailHadnle(data) {
      // 装修范围
      this.detail.range = this.$split(data.range)
      this.range = this.$split(data.decorationRange)
      // 开工条件
      const startCondition = this.$split(data.startCondition)
      this.detail.decorationRange = this.$split(data.decorationRange)
      this.detail.shopDecorationArea = this.$split(data.shopDecorationArea)
      let keys = this.$split('constPicRemark acRemark wpRemark fcRemark horizonRemark', ' ')
      for (const key of keys) {
        if (startCondition.includes(key)) {
          this.$set(this.detail.startCondition, key, true)
        }
      }
      // 其他
      keys = this.$split('range startCondition decorationRange shopDecorationArea', ' ')
      for (const [key, value] of Object.entries(data)) {
        if (keys.includes(key)) {
          continue
        }
        this.$set(this.detail, key, value)
      }
      // 2.装修步骤若原数据为“已终止”时，则步骤不默认填充，需手工选择，且不能选择“已终止”，
      // 装修状态默认“正常”，可手工修改
      if (this.detail.steps === 'M1') {
        this.$set(this.detail, 'steps', '')
        this.$set(this.detail, 'state', 'A')
        this.$set(this.detail, 'schedule', '')
      }
      return this.detail
    },
    selectionChangeHandle(v) {
      this.selections = v
    },
    // 图纸
    changeDrawingHandle(v) {
      this.detail.designPictureDTOS = v
    },
    // 验证数据
    validate() {
      const t = []
      for (const ref of Object.keys(this.$refs)) {
        if (this.$refs[ref].validate) {
          t.push(this.$refs[ref].validate())
        }
      }
      return Promise.all(t)
    },
    // 提交数据处理
    submitDataHandle() {
      return this.validate().then(() => {
        // decorationDTO
        // modelPictureRelationDTOList
        const data = deepClone(this.detail)
        delete data.id
        if (data.designPictureDTOS.length === 0) {
          this.$message.warning('请选择关联图纸')
          return Promise.reject('')
        }
        const files = this.$getFiles(this.files, true, false)
        const _files = files.filter(e => e.dr !== 1 && e.dr !== '1')
        if (_files.length === 0) {
          this.$message.warning('请上传附件')
          return Promise.reject('')
        }
        for (let i = 0; i < _files.length; i++) {
          const f = _files[i]
          if (!f.configAttachmentId) {
            this.$message.warning(`请选择第${i + 1}行附件类型！`)
            return Promise.reject('')
          }
        }
        const checks = Object.entries(data.startCondition || {})
        const startCondition = []
        for (const [k, v] of checks) {
          if (!data.range && data.range.includes('STORES')) {
            data[k] = ''
          }
          if (v) {
            startCondition.push(k)
          }
        }
        data.startCondition = startCondition.join(',')

        data.range = (data.range || []).join(',')
        data.decorationRange = (data.decorationRange || []).join(',')
        data.shopDecorationArea = (data.shopDecorationArea || []).join(',')
        data.files = files
        delete data.decorationTaskCode
        // delete data.constCode
        return data
      })
    },
    confirmHandle() {
      return this.submitDataHandle().then(data => {
        return postAddTask(data).then(res => {
          this.$message.success('操作成功！')
          this.cancelHandle()
        })
      })
    },
    cancelHandle() {
      this.$store.dispatch('views/goFirst')
    },
    // 详情
    getDetail() {
      const { id } = this.$route.query
      if (id === undefined) return
      postSelectByModelId(id).then(res => {
        this.drawData = res.data
      })
      return getGetOneByid(id).then(res => {
        this.detail = this.detailHadnle(res.data)
      })
    },
    // 获取模板
    getTemplate() {
      postConfigAttachmentTemplate().then(res => {
        this.aTList = res.data.records
        // console.log(res)
      })
    },
    stepsChangeHandle(v) {
      this.$set(this.detail, 'schedule', (v || '').replace(/\d+/g, ''))
    }
  }
}
</script>
<style lang="scss" scoped>
.task{

}
.err-offset{
  /deep/ .el-form-item__error{
    margin-left: 310PX;
  }
}
</style>
